package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.oss.enumd.OssBucketOneEnum;
import cn.cdeden.common.oss.enumd.OssModuleType;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.EnterpriseFilesTree;
import cn.cdeden.knowledge.domain.PersonalFilesTree;
import cn.cdeden.knowledge.domain.TreeDownloadFiles;
import cn.cdeden.knowledge.domain.dto.FilesTree;
import cn.cdeden.knowledge.domain.dto.FilesTreeTop;
import cn.cdeden.knowledge.domain.dto.PersonalFilesTreeParam;
import cn.cdeden.knowledge.domain.dto.RecoverFileChooseAPath;
import cn.cdeden.knowledge.domain.vo.FilesSizeType;
import cn.cdeden.knowledge.domain.vo.PersonalFilesTreeVo;
import cn.cdeden.knowledge.enums.TreeTypeEnum;
import cn.cdeden.knowledge.mapper.FilesCollectionMapper;
import cn.cdeden.knowledge.service.EnterpriseFilesTreeService;
import cn.cdeden.knowledge.service.FileService;
import cn.cdeden.knowledge.service.PersonalFilesTreeService;
import cn.cdeden.knowledge.utils.FileUtil;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.knowledge.utils.SetCollectionDataUtil;
import cn.cdeden.resource.api.RemoteFileService;
import cn.cdeden.resource.api.domain.RemoteFile;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final PersonalFilesTreeService personalFilesTreeService;

    @DubboReference(check = false)
    private final RemoteUserService remoteUserService;

    @DubboReference(check = false)
    private final RemoteFileService remoteFileService;

    private final FilesCollectionMapper filesCollectionMapper;

    private final EnterpriseFilesTreeService enterpriseFilesTreeService;


    @Override
    public boolean setTreeTop(FilesTreeTop top) {
        return personalFilesTreeService.lambdaUpdate()
            .in(PersonalFilesTree::getId, top.getIds())
            .eq(PersonalFilesTree::getCreateId, LoginHelper.getUserId())
//            .eq(PersonalFilesTree::getCreateId, FileUserUtils.getUser().getId())
            .isNull(PersonalFilesTree::getDeleteId)
            .set(PersonalFilesTree::getSort, top.isTop() ? -1 : 0)
            .update();
    }

    @Override
    public R fileTreeCopy(RecoverFileChooseAPath chooseAPath) throws BadRequestException {
        LoginUser user = LoginHelper.getLoginUser();
        RemoteUserVo remoteUserVo = remoteUserService.selectUserByUserId(user.getUserId());
        String username = user.getUsername();
        String minioBucket = remoteUserVo.getMinioBucket();
        String userId = Long.toString(user.getUserId());
        List<String> ids = chooseAPath.getIds();
        String parentId = chooseAPath.getParentId();

        QueryWrapper<PersonalFilesTree> wrapper = new QueryWrapper<PersonalFilesTree>()
            .eq("id", parentId).eq("create_id", userId).isNull("delete_id");
        ;
        PersonalFilesTree parentTree = personalFilesTreeService.getOne(wrapper);

        if (ObjectUtils.isEmpty(parentTree)) {
            throw new BadRequestException("错误的文件复制");
        }

        if (StringUtils.equalsIgnoreCase(parentTree.getType(), TreeTypeEnum.FILE.getType())) {
            throw new BadRequestException("错误文件复制位置");
        }

        if (personalFilesTreeService.JudgmentEmpty(ids, parentId)) {
            throw new BadRequestException("目标目录是源文件的子目录");
        }
        Long total = personalFilesTreeService.folderCheck(ids);
        if (remoteUserService.upperLimit(userId, total)) {
            throw new BadRequestException("超出个人文件存储上线 删除回收站数据或者联系管理员添加空间");
        }


        ids.forEach(id -> {
            QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<PersonalFilesTree>()
                .eq("id", id).eq("create_id", userId).isNull("delete_id");
            ;
            PersonalFilesTree filesTree = personalFilesTreeService.getOne(queryWrapper);
            try {
                fileTreeCopy(filesTree, parentTree, userId, username, minioBucket, true);
            } catch (BadRequestException e) {
                e.printStackTrace();
            }
        });

        return R.ok();
    }

    @Override
    public PersonalFilesTree createText(String parentId, String textName) {
        LoginUser user = LoginHelper.getLoginUser(); //用户信息
        String username = user.getUsername();
        String id = Long.toString(user.getUserId());
        PersonalFilesTree parentTree = getPersonalFilesTree(parentId, id); //父树信息
        parentId = Long.toString(parentTree.getId());

        String superiorsIds = parentTree.getSuperiorsIds();
        if (StringUtils.isBlank(superiorsIds)) {
            superiorsIds = parentId;
        } else {
            superiorsIds += "," + parentId;
        }
        if (StringUtils.isBlank(textName)) {
            throw new RuntimeException("文件名不可为空");
        }
        textName = FileUtil.fileNameProcessingException(textName); //处理特殊符号处理
        if (!personalFilesTreeService.judgeIsEmpty(id, username, textName,
            parentId, TreeTypeEnum.RICHTEXT.getType(), null)) {
            throw new RuntimeException("文件,名称重复");
        }

        PersonalFilesTree tree = new PersonalFilesTree(id, username);
        tree.setRealName(textName);
        tree.setType(TreeTypeEnum.RICHTEXT.getType());
        tree.setSuffix(TreeTypeEnum.RICHTEXT.getType());
        tree.setParentId(parentId);
        tree.setPath(parentTree.getPath() + "/" + textName);
        tree.setSuperiorsPath(parentTree.getPath());
        tree.setSuperiorsIds(superiorsIds);
        tree.setTopParentId(parentTree.getTopParentId());
        boolean save = personalFilesTreeService.save(tree);
        if (save) {
            return tree;
        } else {
            return null;
        }

    }

    @Override
    public boolean updateName(String id, String folderName) throws BadRequestException {
        LoginUser user = LoginHelper.getLoginUser();//用户信息
//        FileUserDto user = FileUserUtils.getUser(); //用户信息
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());
        PersonalFilesTree tree = personalFilesTreeService.getById(id);
        if (ObjectUtils.isEmpty(tree)) {
            throw new BadRequestException("错误的文件编号");
        }
        if (!StringUtils.equalsIgnoreCase(tree.getCreateId(), userId)) {
            throw new BadRequestException("你不是该文件的拥有者不可修改");
        }
        if (StringUtils.equalsIgnoreCase(tree.getRealName(), folderName)) {
            throw new BadRequestException("文件名重复修改名重复");
        }
        if (!personalFilesTreeService.judgeIsEmpty(userId, username, folderName, tree.getParentId(), tree.getType(), tree.getSuffix())) {
            throw new BadRequestException("文件名称重复");
        }
        String path = tree.getPath();
        String newPath = tree.getSuperiorsPath() + "/" + folderName;
        UpdateWrapper<PersonalFilesTree> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("real_name", folderName)
            .set("update_id", userId)
            .set("path", newPath)
            .set("update_by", username)
            .set("update_time", new Date())
            .eq("id", id);
        personalFilesTreeService.update(updateWrapper);

        return personalFilesTreeService.updatePath(userId, username, path, newPath, id, false);
    }

    @Override
    public boolean upDateFolderSizeUpDate(String userId, PersonalFilesTree filesTree, Long originalSize, Long newSize, String type) {
        try {
            if (ObjectUtils.isEmpty(newSize)) {
                return true;
            }
            if (StringUtils.equalsIgnoreCase(type, FilesSizeType.AddSize)) { //添加
//                log.info("添加用户空间,开始");
                //用户
                remoteUserService.updateStorageSum(userId, newSize);
//                userService.updateStorageSum(userId, newSize);
                //上级文件夹的
                personalFilesTreeService.upDateFolderSize(filesTree, type);
//                log.info("添加用户空间,结束");
            } else if (StringUtils.equalsIgnoreCase(type, FilesSizeType.DeleteSize)) { //删除
//                log.info("删除用户空间");
                //用户
                remoteUserService.updateStorageLess(userId, newSize);
                //上级文件夹的
                personalFilesTreeService.upDateFolderSize(filesTree, type);
//                log.info("删除用户空间,结束");
            } else if (StringUtils.equalsIgnoreCase(type, FilesSizeType.UpDataSize)) { //修改

                if (ObjectUtils.isEmpty(originalSize)) {
                    return true;
                }
//                log.info("修改用户空间");
                //用户
                remoteUserService.updateStorageUpDate(userId, originalSize, newSize);
                //上级文件夹的
                personalFilesTreeService.upDateFolderSizeUpDate(filesTree, originalSize, newSize);
//                log.info("修改用户空间,结束");
            }
        } catch (Exception e) {
            throw new RuntimeException("保存文件失败修改空间大小:" + e.getMessage());
//            throw new BadRequestException("保存文件失败修改空间大小:" + e.getMessage());
        }

        return true;
    }

    @Override
    public PersonalFilesTreeVo selectPersonalTree(String id) throws BadRequestException {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser(); //用户信息
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());
        PersonalFilesTree personalFilesTree = getPersonalFilesTree(id, userId); //父树信息
        PersonalFilesTreeVo vo = MapstructUtils.convert(personalFilesTree, PersonalFilesTreeVo.class);
//        PersonalFilesTreeVo vo = ConvertUtil.convert(personalFilesTree, PersonalFilesTreeVo.class);
        List<PersonalFilesTree> childrenTree = personalFilesTreeService.selectPersonalTree(id);
        List<PersonalFilesTreeVo> children = new ArrayList<>();
        for (PersonalFilesTree filesTree : childrenTree) {
            PersonalFilesTreeVo personalFilesTreeVo = selectPersonalTree(String.valueOf(filesTree.getId()));
            children.add(personalFilesTreeVo);
        }
        vo.setChildren(children);
        return vo;
    }

    @Override
    public PersonalFilesTree getPersonalFilesTree(String parentId, String id) {
        return personalFilesTreeService.getPersonalFilesTree(parentId, id);
    }

    @Override
    public R fileTreeMove(RecoverFileChooseAPath chooseAPath) throws BadRequestException {
        LoginUser user = LoginHelper.getLoginUser();
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());
        String parentId = chooseAPath.getParentId();
        List<String> ids = chooseAPath.getIds();
        QueryWrapper<PersonalFilesTree> query = new QueryWrapper<PersonalFilesTree>()
            .eq("id", parentId)
            .eq("create_id", userId)
            .isNull("delete_id");
        PersonalFilesTree parentTree = personalFilesTreeService.getOne(query);


        if (ObjectUtils.isEmpty(parentTree)) {
            throw new BadRequestException("文件错误的移动");
        }

        if (StringUtils.equalsIgnoreCase(parentTree.getType(), TreeTypeEnum.FILE.getType())) {
            throw new BadRequestException("错误文件文件移动位置");
        }
        if (personalFilesTreeService.JudgmentEmpty(ids, parentId)) {
            throw new BadRequestException("目标目录是源文件的子目录");
        }


//        int
        List<PersonalFilesTree> success = new ArrayList<>();
        List<PersonalFilesTree> exception = new ArrayList<>();

        ids.forEach(id -> {
            QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<PersonalFilesTree>()
                .eq("id", id)
                .eq("create_id", userId)
                .isNull("delete_id");
            //获取要移动的文件
            PersonalFilesTree filesTree = personalFilesTreeService.getOne(queryWrapper);
            boolean b = false;
            if (ObjectUtils.isNotEmpty(filesTree)) {
                b = fileTreeMove(parentTree, filesTree, userId, username);
            }
            if (b) {
                success.add(filesTree);
            } else {
                exception.add(filesTree);
            }
        });
        if (CollectionUtils.isNotEmpty(exception) && exception.size() > 0) {
            StringBuilder message = new StringBuilder();
            StringJoiner joiner = new StringJoiner(",");
            if (CollectionUtils.isNotEmpty(success) && success.size() > 0) {
                message.append(success.size() + "个对象移动成功,");
                int j = 0;
                for (int i = 0; i < ((exception.size() > 3) ? 3 : exception.size()); i++) {
                    PersonalFilesTree tree = exception.get(i);
                    joiner.add(tree.getRealName());
                }
                message.append(joiner);
                message.append("等");
                message.append(exception.size());
                message.append("对象移动失败");
            } else {
                for (int i = 0; i < ((exception.size() > 3) ? 3 : exception.size()); i++) {
                    PersonalFilesTree tree = exception.get(i);
                    joiner.add(tree.getRealName());
                }
                message.append(joiner);
                message.append("等,");
                message.append("失败文件移动");
                message.append(exception.size() + "个");
            }
            return R.ok(message.toString());
//            return BaseRespResult.successResult(null, RespResultEnums.HINT, message.toString());
        } else {
            return R.ok("移动成功");
//            return BaseRespResult.successResult(null, "移动成功");
        }
    }

    @Override
    public boolean updateRemarks(String id, String remarks) throws BadRequestException {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser(); //用户信息
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());
        PersonalFilesTree tree = personalFilesTreeService.getById(id);
        if (ObjectUtils.isEmpty(tree)) {
            throw new BadRequestException("错误的文件编号");
        }
        if (!StringUtils.equalsIgnoreCase(tree.getCreateId(), userId)) {
            throw new BadRequestException("你不是该文件的拥有者不可修改");
        }

        return personalFilesTreeService.lambdaUpdate()
            .eq(PersonalFilesTree::getId, id)
            .set(PersonalFilesTree::getRemarks, remarks)
            .update();
    }

    @Override
    public PersonalFilesTreeVo selectPersonalTree(PersonalFilesTreeParam query) {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser(); //用户信息
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());

        if (StringUtils.isNotEmpty(query.getType()) && StringUtils.equalsIgnoreCase(query.getType(), "11")) {
            LoginHelper.getLoginUserByUserId(user.getUserId());

            //改写判断权限的方法
            boolean check = remoteUserService.checkPerm(user.getUserId(), "fileManage:recycle:list");


//            boolean superAdmin = LoginHelper.isSuperAdmin(user.getUserId());
//            Boolean check = el.check("recycle:tree"); //返回文件的权限
//            Boolean check = true;
            //
            if (!check) {
                throw new RuntimeException("没有权限访问");
            }

            String username1 = query.getUsername();

            RemoteUserVo userDto = remoteUserService.selectUserByUserName(username1);
//            FileUserDto userDto = FileUserUtils.getUser(username1);//用户信息
            //校验权限
//            username = userDto.getUsername();
            username = userDto.getUserName();
            userId = Long.toString(userDto.getUserId());
        }
        PersonalFilesTree parentTree = getPersonalFilesTree(query.getParentId(), userId); //父树信息

        if (StringUtils.isEmpty(query.getParentId())) {
            query.setParentId(String.valueOf(parentTree.getId()));
        }
        List<PersonalFilesTree> personalFilesTrees = personalFilesTreeService.selectPersonalTree(query, userId);
        List<PersonalFilesTree> filesTrees = getInfo(personalFilesTrees); //信息

        List<PersonalFilesTreeVo> vos = MapstructUtils.convert(filesTrees, PersonalFilesTreeVo.class);
        PersonalFilesTreeVo convert = MapstructUtils.convert(parentTree, PersonalFilesTreeVo.class);
        convert.setChildren(vos);
        return convert;
    }

    @Override
    public boolean personalToEnterprise(Long fileId, String parentId, String fileName) {
        LoginUser user = LoginHelper.getLoginUser();
        //根据个人文档中的id查询出源文件的所有信息
        PersonalFilesTree personalFilesTree = personalFilesTreeService.selectById(fileId.toString());

        //根据parentId查询出企业文档上级文件夹的信息
        EnterpriseFilesTree newEnterpriseFilesTree = enterpriseFilesTreeService.getOne(new LambdaQueryWrapper<EnterpriseFilesTree>().eq(EnterpriseFilesTree::getId, Long.valueOf(parentId)));

        //判断提交的是文件夹还是文件

        //提交的是文件的情况
        if (personalFilesTree.getType().equals("folder")) {

            //将个人文档的文件 复制到企业库中
            RemoteFile remoteFile = new RemoteFile();
            remoteFile.setOssId(Long.valueOf(personalFilesTree.getStorageId()));
            RemoteFile newRemoteFile = remoteFileService.copyFile(remoteFile, OssBucketOneEnum.ENTERPRISE_BUCKET.getCode(), OssModuleType.Enterprise);
            //将信息存入企业库中
            EnterpriseFilesTree enterpriseFilesTree = new EnterpriseFilesTree();
            enterpriseFilesTree.setParentId(parentId);
            enterpriseFilesTree.setSuffix(newRemoteFile.getFileSuffix());
            enterpriseFilesTree.setRealName(fileName);
            enterpriseFilesTree.setSuperiorsPath(newEnterpriseFilesTree.getPath());
            enterpriseFilesTree.setPath(enterpriseFilesTree.getSuperiorsPath() + "/" + fileName);
            enterpriseFilesTree.setType("file");
            enterpriseFilesTree.setStorageId(newRemoteFile.getOssId().toString());
            enterpriseFilesTree.setSize(newRemoteFile.getFileSize());
            enterpriseFilesTree.setCreateId(user.getUserId().toString());
            enterpriseFilesTree.setCreateBy(user.getUsername());
            enterpriseFilesTree.setCreateTime(new Date());
            enterpriseFilesTree.setUpdateId(user.getUserId().toString());
            enterpriseFilesTree.setUpdateBy(user.getUsername());
            enterpriseFilesTree.setEdition(newRemoteFile.getVersionId());
            enterpriseFilesTree.setEditionName(newRemoteFile.getVersionName());
            enterpriseFilesTree.setRemarks(personalFilesTree.getRemarks());
            //数据存入企业库中
            enterpriseFilesTreeService.save(enterpriseFilesTree);
            //修改所有上级文件的大小
            enterpriseFilesTreeService.setParentNodeSize(parentId, enterpriseFilesTree.getSize(), 0);

            //新增es数据

            return true;
        }

        //提交的是文件夹的情况,先查询出该文件夹下所有的文件和文件夹数据
        Long id = personalFilesTree.getId();
        //所有要提交的文件
        List<PersonalFilesTree> allChildById = personalFilesTreeService.getAllChildById(id);
        //先将文件夹在企业文档中创建好
        EnterpriseFilesTree folder = new EnterpriseFilesTree();
        folder.setParentId(parentId);
        folder.setRealName(fileName);
        folder.setSuperiorsPath(newEnterpriseFilesTree.getPath());
        folder.setPath(folder.getSuperiorsPath() + "/" + fileName);
        folder.setType("folder");
        folder.setCreateId(user.getUserId().toString());
        folder.setCreateBy(user.getUsername());
        folder.setCreateTime(new Date());
        folder.setUpdateId(user.getUserId().toString());
        folder.setUpdateBy(user.getUsername());
        folder.setRemarks(personalFilesTree.getRemarks());
        enterpriseFilesTreeService.save(folder);

        //记录旧的父级id与新的父级id的对应关系



        return false;
    }

    @Override
    public PersonalFilesTreeVo selectPersonalTreePage(PersonalFilesTreeParam query, Pageable pageable) {
        LoginUser user = LoginHelper.getLoginUser();
//        FileUserDto user = FileUserUtils.getUser(); //用户信息
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());

        if (StringUtils.isNotEmpty(query.getType()) && StringUtils.equalsIgnoreCase(query.getType(), "11")) {
            RemoteUserVo userDto = remoteUserService.selectUserByUserId(Long.valueOf(userId));
//            FileUserDto userDto = FileUserUtils.getUser(username);//用户信息
            //校验权限
            username = userDto.getUserName();
            userId = Long.toString(userDto.getUserId());
        }

        PersonalFilesTree parentTree = getPersonalFilesTree(query.getParentId(), userId); //父树信息


        if (StringUtils.isEmpty(query.getParentId())) {
            query.setParentId(String.valueOf(parentTree.getId()));
        }
        IPage<PersonalFilesTree> personalFilesTreeIPage = personalFilesTreeService.selectPersonalTreePage(query, userId, pageable);
        List<PersonalFilesTree> filesTrees = getInfo(personalFilesTreeIPage.getRecords()); //信息

        List<PersonalFilesTreeVo> vos = MapstructUtils.convert(filesTrees, PersonalFilesTreeVo.class);
//        List<PersonalFilesTreeVo> vos = ConvertUtil.convertList(filesTrees, PersonalFilesTreeVo.class);
        PersonalFilesTreeVo convert = MapstructUtils.convert(parentTree, PersonalFilesTreeVo.class);
//        PersonalFilesTreeVo convert = ConvertUtil.convert(parentTree, PersonalFilesTreeVo.class);
        convert.setChildren(vos);
        convert.setCount(personalFilesTreeIPage);
//        convert.setPageCount();
        return convert;
    }

    @Override
    public TableDataInfo<PersonalFilesTreeVo> selectTreePage(PersonalFilesTreeParam query, Pageable pageable) {
        LoginUser user = LoginHelper.getLoginUser();
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());
        if (StringUtils.isNotEmpty(query.getType()) && StringUtils.equalsIgnoreCase(query.getType(), "11")) {
            RemoteUserVo userDto = remoteUserService.selectUserByUserName(username);
            //校验权限
            username = userDto.getUserName();
            userId = Long.toString(userDto.getUserId());
        }
        query.setUserId(userId);
        query.setUsername(username);

        TableDataInfo<PersonalFilesTreeVo> personalFilesTreeVoTableDataInfo = personalFilesTreeService.selectTreePage(query, pageable);
        List<PersonalFilesTreeVo> rows = personalFilesTreeVoTableDataInfo.getRows();
        List<PersonalFilesTree> convert = MapstructUtils.convert(rows, PersonalFilesTree.class);
        if (CollectionUtils.isNotEmpty(rows)) {
            List<PersonalFilesTree> filesTrees = getInfo(convert);
            personalFilesTreeVoTableDataInfo.setRows(MapstructUtils.convert(filesTrees, PersonalFilesTreeVo.class));
        }
        return personalFilesTreeVoTableDataInfo;
    }

    @Override
    public IPage<PersonalFilesTree> selectFilesTree(Collection<String> ids, String fileNam, Pageable pageable) {
        IPage<PersonalFilesTree> mybatisPage = PageUtil.toMybatisPage(pageable);
        IPage<PersonalFilesTree> page = personalFilesTreeService.lambdaQuery()
            .in(PersonalFilesTree::getId, ids)
            .isNull(PersonalFilesTree::getDeleteId)
            .like(StringUtils.isNotBlank(fileNam), PersonalFilesTree::getRealName, fileNam)
            .page(mybatisPage);
        return page;
    }

    /**
     * @param trees
     * @return java.util.List<com.cdyd.ecm.modules.personal.domain.PersonalFilesTree>
     * @author Yu.
     * @Description // 获取关注和收藏信息
     * @Date 2023/11/8 19:04
     **/
    private List<PersonalFilesTree> getInfo(List<PersonalFilesTree> trees) {
        if (ObjectUtils.isNotEmpty(trees)) {
            SetCollectionDataUtil setCollectionDataUtil = new SetCollectionDataUtil(filesCollectionMapper);
//            SetAttentionDataUtil setAttentionDataUtil = new SetAttentionDataUtil(filesAttentionMapper);
            trees = setCollectionDataUtil.setCollectionPersonalData(trees);//获取收藏
//            trees = setAttentionDataUtil.setAttentionPersonalData(trees);//获取关注
        }
        return trees;

    }


    private boolean fileTreeMove(PersonalFilesTree parentTree, PersonalFilesTree filesTree, String userId, String username) {
        String realName = filesTree.getRealName();
        String id = Long.toString(filesTree.getId());
        String parentId = Long.toString(parentTree.getId());
        String superiorsIds = parentTree.getSuperiorsIds();
        if (StringUtils.isBlank(superiorsIds)) {
            superiorsIds = parentId;
        } else {
            superiorsIds += "," + parentId;
        }

        if (StringUtils.equalsAnyIgnoreCase(filesTree.getParentId(), parentId)) {
            return false;
        }

        Boolean aBoolean = personalFilesTreeService.judgeIsEmpty(userId, username, realName, parentId, filesTree.getType(), filesTree.getSuffix());
        if (!aBoolean) {
            realName += "_" + System.currentTimeMillis();
        }


        String treePath = filesTree.getPath();
        String superiorsIds1 = filesTree.getSuperiorsIds(); //原来的上级文件夹ID


        String parentTreePath = parentTree.getPath();
        String newPath = parentTreePath + "/" + realName;
        // 删除原本上级文件夹的空间大小
        personalFilesTreeService.upDateFolderSize(filesTree, FilesSizeType.DeleteSize);

        filesTree.setSuperiorsIds(superiorsIds);
        LambdaUpdateWrapper<PersonalFilesTree> updateWrapper = new LambdaUpdateWrapper<PersonalFilesTree>()
            .set(PersonalFilesTree::getSuperiorsIds, superiorsIds)//设置上级IDs
            .set(PersonalFilesTree::getRealName, realName)//设置名字
            .set(PersonalFilesTree::getPath, newPath)//设置路径
            .set(PersonalFilesTree::getSuperiorsPath, parentTreePath)//设置父路径
            .set(PersonalFilesTree::getParentId, parentId)//设置父编号
            .set(PersonalFilesTree::getUpdateId, userId)
            .set(PersonalFilesTree::getUpdateBy, username)
            .set(PersonalFilesTree::getUpdateTime, new Date())
            .eq(PersonalFilesTree::getId, filesTree.getId());
        personalFilesTreeService.update(updateWrapper);

//        添加移动文件夹的空间大小
        personalFilesTreeService.upDateFolderSize(filesTree, FilesSizeType.AddSize);
        //修改儿子路径 //和上级的id
        personalFilesTreeService.updatePathID(userId, username, treePath, superiorsIds1, newPath, superiorsIds, String.valueOf(filesTree.getId()), false);
        return true;
    }






    private void fileTreeCopy(PersonalFilesTree filesTree, PersonalFilesTree parentTree, String userId, String username, String minioBucket, boolean b) throws BadRequestException {
        String parentPath = parentTree.getPath();
        PersonalFilesTree newTree = filesTree.filesCopy(userId, username);
        newTree.setSuperiorsPath(parentPath);
        String parentId = Long.toString(parentTree.getId());
        newTree.setParentId(parentId);
        newTree.setType(filesTree.getType());
        String superiorsIds = parentTree.getSuperiorsIds();
        if (StringUtils.isBlank(superiorsIds)) {
            superiorsIds = parentId;
        } else {
            superiorsIds += "," + parentId;
        }
        newTree.setSuperiorsIds(superiorsIds);


        String realName = newTree.getRealName();
        if (b) {
            Boolean aBoolean = personalFilesTreeService.judgeIsEmpty(userId, username, realName,
                parentId, newTree.getType(), newTree.getSuffix());
            if (!aBoolean) {
                realName += "_" + System.currentTimeMillis();
            }
            newTree.setRealName(realName);
        }

        newTree.setPath(parentPath + "/" + realName);
        personalFilesTreeService.save(newTree);

        if (StringUtils.equalsIgnoreCase(newTree.getType(), TreeTypeEnum.FILE.getType())) {
            fileCopy(newTree, minioBucket);
        } else {
            folderCopy(String.valueOf(filesTree.getId()), newTree, minioBucket);
        }
    }

    private void fileCopy(PersonalFilesTree filesTree, String minioBucket) throws BadRequestException {
        RemoteFile remoteFile = new RemoteFile();
        remoteFile.setOssId(Long.valueOf(filesTree.getStorageId()));
        remoteFile.setVersionId(filesTree.getEdition());
        remoteFile.setVersionName(filesTree.getEditionName());
        remoteFile.setFileSize(filesTree.getSize());
        remoteFile.setFileSuffix(filesTree.getSuffix());
        RemoteFile remoteFile1 = remoteFileService.copyFile(remoteFile, minioBucket, OssModuleType.Personal);
        boolean b = personalFilesTreeService.updateById(filesTree);
        if (b) {
            //修改用户使用文件大小
            upDateFolderSizeUpDate(filesTree.getCreateId(), filesTree, null, filesTree.getSize(), FilesSizeType.AddSize); //复制
        }
    }




    private void folderCopy(String filesTreeId, PersonalFilesTree newTree, String minioBucket) {
//        filesTreeId
        QueryWrapper<PersonalFilesTree> queryWrapper = new QueryWrapper<PersonalFilesTree>()
            .eq("parent_id", filesTreeId)
            .eq("create_id", newTree.getCreateId())
            .isNull("delete_id");
        List<PersonalFilesTree> filesTrees = personalFilesTreeService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(filesTrees)) {
            filesTrees.forEach(tree -> {
                try {
                    fileTreeCopy(tree, newTree, newTree.getCreateId(), newTree.getCreateBy(), minioBucket, false);
                } catch (BadRequestException e) {
                    e.printStackTrace();
                }
            });
        }
    }



}
